<?php
	
/**
 * Project: CrazyPoems
 * Author: Alexandru
 * Date: 20/10/2008
 * File: functions.register.php
 */
 
function validateUserName() {
	global $error_msg, $username;
	if (strlen($username) > 2 && strlen($username) < 26) { // Check size 3-25
		$username = strtolower($username);
		if (!preg_match("/^([a-zA-Z0-9_])+$/", $username)) {
			$error_msg .= "<p>Username-ul poate contine doar litere de la A la Z, numere de la 0 la 9 si liniuta de jos '_'.</p>";
		} else {
			// Is username available?
			$q = mysql_query("SELECT id FROM ".TABLE_USERS." WHERE username = '$username'") or die(mysql_error());
			$r = mysql_fetch_row($q);
			if ($r) {
				$error_msg .= "<p>Username-ul ales a fost luat deja, alege altul.</p>";
			}
		}
	} else {
		$error_msg .= "<p>Trebuie sa iti alegi un Username, marimea de la 2 la 25 litere.</p>";
	}
}

function validateEmailAddress() {
	global $error_msg, $email, $email2, $validateEmailAddressMode;
	if (strlen($email) > 0) {
		$email = strtolower($email);
		$email2 = strtolower($email2);
		if ($email == $email2) {
			if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\.\\+=_-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email)) {
				$error_msg .= "<p>Adresa de e-mail trebuie sa fie valida.</p>";
			} else {
				// Is email available?
				$q = mysql_query("SELECT id FROM ".TABLE_USERS." WHERE email = '$email'") or die(mysql_error());
				$r = mysql_fetch_row($q);
				if ($r) {
					$error_msg .= "<p>Adresa de e-mail introdusa a fost folosita deja, alege alta.</p>";
				}
			}
		} else {
			$error_msg .= "<p>Adresele de e-mail trebuie sa fie identice.</p>";
		}
	} else {
		$error_msg .= "<p>Introdu adresa de e-mail.</p>";
	}
}

function Hop_newUser($username, $fullname, $email, $password) {
	global $smarty, $cookie;
	$q = mysql_query("INSERT INTO ".TABLE_USERS."(username, fullname, email, password, member_since, last_login, admin) values('$username','".checkSQL($fullname)."','$email','".md5($password)."','".get_current_time()."','".get_current_time()."', 0)") or die(mysql_error());
	// Log user in.
	$cookie->username = $username;
	$cookie->fullname = $fullname;
	$cookie->email = $email;
	$smarty->assign('session_username', $username);
	$smarty->assign('session_fullname', $fullname);
	$smarty->assign('session_email', $email);
	// Send welcome email.
	$welcome = "Salut $fullname,\n\n";
	$welcome .="Bine ai venit la CrazyPoems, numele tau de utilizator este '$username' iar parola '$password', multumim pentru ca te-ai alaturat!\n\n";
	$welcome .="Happy reading and writing,\n";
	$welcome .=MAIL_URL;
	if (mail($email,"Bine ai venit la CrazyPoems",$welcome,"From: \"Crazy Poems\"<no-reply@crazypoems.net>\nReply-to: \"Crazy Poems\"<no-reply@crazypoems.net>")) {
		// echo 'email sent';
	} else {
		// echo 'email not sent';
	}
}

function Hop_editAccount($username, $fullname, $password) {
	global $smarty, $cookie;
	$errors = "";
	
	// Update info.
	$c = "UPDATE ".TABLE_USERS." SET fullname = '".checkSQL($fullname)."', lang = '".$_POST['lang']."'";
	if (strlen($password) > 0) {
		$c .= ", password = '".md5($password)."'";
	}
	
	// Profile photo.
  if( (!empty($_FILES["profile_image"])) && ($_FILES['profile_image']['error'] == 0) ) {
    $filename = basename($_FILES['profile_image']['name']);
    $ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
    $allowed_ext = array("jpeg", "jpg");
    $allowed_type = array("image/jpeg", "image/pjpeg");
    $allowed_size = 4194304; // 4 mb
    if ((array_search($ext, $allowed_ext) !== false) && (array_search($_FILES["profile_image"]["type"], $allowed_type) !== false) && ($_FILES["profile_image"]["size"] < $allowed_size)) {
      $newname = $username.time().".jpg";
      // Resize.
      // $uploadedfile = $_FILES['profile_image']['tmp_name'];
      
	// New resize.
	include_once('images.inc.php');
	if (!imageResize($_FILES['profile_image'], USER_PHOTO_PATH.$newname, 120, 120)) {
		$errors .= "<p>Nu s-a putut salva poza, anuntati administratorul prin formularul de contact!</p>";
	}
      
      // Create an Image from it so we can do the resize
      // $src = imagecreatefromjpeg($uploadedfile);
      // Capture the original size of the uploaded image
      // list($width,$height)=getimagesize($uploadedfile);
      // For our purposes, I have resized the image to be
      // 600 pixels wide, and maintain the original aspect
      // ratio. This prevents the image from being "stretched"
      // or "squashed". If you prefer some max width other than
      // 600, simply change the $newwidth variable
      // $newwidth=120;
      // $newheight=($height/$width)*$newwidth;
      // $tmp=imagecreatetruecolor($newwidth,$newheight);
      // this line actually does the image resizing, copying from the original
      // image into the $tmp image
      // imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
      // now write the resized image to disk. I have assumed that you want the
      // resized, uploaded image file to reside in the ./images subdirectory.
			// Delete old if exists.
			// if (file_exists(USER_PHOTO_PATH.$newname)) { // FIXME: Hacer que elimine la que esta en la base de datos
			  // echo "deleting old..";
			//	unlink(USER_PHOTO_PATH.$newname);
			//}
      // $filename = USER_PHOTO_PATH.$newname;
      // imagejpeg($tmp,$filename,100);
      // imagedestroy($src);
      // imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
      									// has completed.
      // Save to db.
      $c .= ", photo = '".$newname."'";
    } else {
			$errors .= "<p>Poza trebuie sa fie format JPEG iar marimea maxima este de 4mb.</p>";
		}
  }
	
	$c .=" WHERE username = '$username'";
	$q = mysql_query($c) or die(mysql_error());
	// Assign to session.
	$cookie->fullname = $fullname;
	$cookie->lang = $_POST['lang'];
	$smarty->assign('session_fullname', $fullname);
	
	return $errors;
	
}
	
?>
